//购物车相关逻辑
import { computed } from 'vue'
import { toRefs } from 'vue'
import { useStore } from 'vuex'
export const useCommonCartEffect = (shopId) => {
    const store = useStore()
    //const { cartList } = toRefs(store.state)
    const cartList = store.state.cartList;
    const changeCartItemInfo = (shopId, productId, productInfo, num) => {
        //点击加入购物车
        store.commit('changeCartItemInfo', {
            shopId,
            productId,
            productInfo,
            num
        }) 
        //console.log(shopId, productId, productInfo)
    }

    const productList = computed(()=> {
        const productList = cartList[shopId]?.productList || {}
        // const notEmptyProductList = {}
        // for(let i in productList) {
        //     const product = productList[i]
        //     if(product.count > 0) {
        //         notEmptyProductList[i] = product
        //     }
        // }
        return productList
    })

    const shopName = computed(()=> {
        const shopName = cartList[shopId]?.shopName || ''
        return shopName
    })

    const calculations = computed(() => {
        const productList = cartList[shopId]?.productList
        const result = { total: 0, price: 0, allChecked: true}
        // let total = 0//总数
        // let price = 0//总计
        // let allChecked = true//默认是全选的
        if(productList) {
            for(let i in productList) {
                const product = productList[i]
                result.total += product.count
                if(product.check) {
                    result.price += (product.count * product.price)
                }
                //没有全部选中的时候
                if( product.count > 0 && !product.check) {
                   result.allChecked = false
                }
            }
        }
        result.price = result.price.toFixed(2)
        return result
    })

    return { cartList, changeCartItemInfo, productList, shopName, calculations }
}